<template>
  <div
    v-loading="product.list.loading"
    id="virtualSubnet"
    class="main-div main-div-nopadding"
  >
    <el-container>
      <el-aside
        style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
        class="background-color-white"
      >
        <div class="aside-header-div">
          <!--更新包管理-->
          {{ $t('message.cpm.aside.header') }}
          <div style="float: right">
            <el-button
              v-if="$store.state.is_staff"
              @click="handleProductCreate"
              style="padding: 0"
              type="text"
            >
              <i
                class="el-icon-plus"
                style="font-weight: bold;color: #fff;padding-right: 45px;line-height: 1em;"
              />
            </el-button>
          </div>
        </div>
        <div
          class="aside-tree-div"
        >
          <!--product list-->
          <el-table
            row-class-name="my-table-cell-pointer"
            @row-click="handleProductRowClick"
            :data="product.list.data"
            highlight-current-row
            :show-header="false"
          >
            <el-table-column
              type="index"
              width="50px"
            />
            
            <el-table-column prop="kind" />
            <el-table-column
              v-if="$store.state.is_staff"
              width="100px"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="$store.state.is_staff"
                  v-show="!scope.row.create"
                  style="padding: 0 0 0 5px"
                  @click.stop="handleProductDelete(scope.$index, scope.row)"
                  type="text"
                >
                  <!--删除-->
                  <img src="@/assets/common/delete.png">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-aside>
      <el-main
        v-loading="update_package.list.loading"
        class="el-main-padding my-test"
      >
        <div class="my-breadcrumb-div">
          <i class="el-icon-location my-breadcrumb-icon my-breadcrumb-padding" />
          <el-breadcrumb
            class="my-breadcrumb-padding"
            separator="/"
          >
            <el-breadcrumb-item>
              <!--系统-->
              {{ $t('message.cpm.breadcrumb.crumb1') }}
            </el-breadcrumb-item>
            <el-breadcrumb-item>
              <!--更新包管理-->
              {{ $t('message.cpm.breadcrumb.crumb2') }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <el-row v-show="!!product.currentRow">
          <el-col>
            <div
              class="margin-bottom-row"
              style="text-align: left"
            >
              <el-button
                v-if="$store.state.is_staff"
                @click="handleUpdatePackageCreate"
                type="primary"
                size="small"
              >
                <!--添加更新包-->
                {{ $t('message.cpm.main.addButton') }}
              </el-button>
            </div>
          </el-col>
        </el-row>
        <!--更新包-->
        <el-row>
          <el-col
            v-for="(item,index) in update_package.list.data"
            :key="item.id"
          >
            <el-card class="margin-bottom-row">
              <div
                class="my-package-div card-title font-size-el line-height-none"
              >
                <div>{{ item.package_version }}</div>
                <div>{{ $service.convertTimeToShow(item.upload_datetime) }}</div>
              </div>
              <!--描述-->
              <div class="my-package-div-describe">
                {{ item.describe }}
              </div>
              <!--操作-->
              <div class="my-package-div-button">
                <el-button
                  v-if="$store.state.is_staff"
                  @click="handleUpdatePackageDelete(index, item)"
                  type="danger"
                  size="small"
                >
                  <!--删除-->
                  {{ $t('message.common.button.delete') }}
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!--dialog-->
    <div>
      <!--product-->
      <!--产品-->
      <el-dialog
        style="text-align: left"
        :title="$t('message.cpm.dialog.product.title')"
        width="350px"
        :visible.sync="dialog.product.visible"
      >
        <el-form
          ref="productForm"
          :model="dialog.product.form"
          :rules="dialog.product.rules"
          label-width="100px"
        >
          <!--产品名称-->
          <el-form-item
            :label="$t('message.cpm.dialog.product.form.kind')"
            prop="kind"
          >
            <el-input
              :maxlength="$store.state.parameters.inputLengthLimit.text"
              show-word-limit
              v-model="dialog.product.form.kind"
            />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
            v-loading="dialog.product.buttonLoading"
            @click="submitForm('productForm')"
            type="primary"
          >
            <!--确定-->
            {{ $t('message.common.button.confirm') }}
          </el-button>
        </div>
      </el-dialog>
      <!--更新包-->
      <el-dialog
        style="text-align: left"
        :title="$t('message.cpm.dialog.update_package.title')"
        width="400px"
        :visible.sync="dialog.update_package.visible"
      >
        <el-form
          ref="updatePackageForm"
          :model="dialog.update_package.form"
          :rules="dialog.update_package.rules"
          label-width="80px"
        >
        
          <!--版本号-->
          <el-form-item :label="$t('message.cpm.dialog.update_package.form.version')">
            <el-form-item
              class="form-item-33-width"
              prop="first"
            >
              <el-input
                size="mini"
                class="version-input"
                maxlength="2"
                v-model.number="dialog.update_package.form.first"
              />.
            </el-form-item>
            <el-form-item
              class="form-item-33-width"
              prop="second"
            >
              <el-input
                size="mini"
                class="version-input"
                maxlength="2"
                v-model.number="dialog.update_package.form.second"
              />.
            </el-form-item>
            <el-form-item
              class="form-item-33-width"
              prop="third"
            >
              <el-input
                size="mini"
                class="version-input"
                maxlength="2"
                v-model.number="dialog.update_package.form.third"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item label="File">
            <!--上传文件-->
            <form
              style="width: 200px;display: inline-block"
              enctype="multipart/form-data"
              id="uploadImg"
            >
              <input
                name="file"
                type="file"
                id="file"
              >
            </form>
          </el-form-item>
          <!--描述-->
          <el-form-item :label="$t('message.cpm.dialog.update_package.form.describe')">
            <el-input
              style="width: 100%;"
              size="mini"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
              v-model="dialog.update_package.form.describe"
            />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
            v-loading="dialog.update_package.buttonLoading"
            @click="submitUpdatePackage('updatePackageForm')"
            type="primary"
          >
            <!--确定-->
            {{ $t('message.common.button.confirm') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Cpm',
  data () {
    return {
      product: {
        currentRow: null,

        list: {
          loading: false,
          data: []
        }
      },

      update_package: {
        list: {
          loading: false,
          data: []
        }
      },

      dialog: {
        product: {
          visible: false,
          buttonLoading: false,

          method: '',
          id: '',
          form: {
            kind: ''
          },
          rules: {
            kind: [
              // 请输入产品名称
              { required: true, message: this.$t('message.cpm.validate.product.kind'), trigger: 'blur' }
            ]
          }
        },

        update_package: {
          visible: false,
          buttonLoading: false,

          method: '',
          id: '',
          form: {
            first: '',
            second: '',
            third: '',
            describe: ''
          },
          rules: {
            first: [
              // 请输入版本号
              { required: true, message: this.$t('message.cpm.validate.update_package.version.err1'), trigger: 'blur' },
              // 请输入正整数
              { type: 'integer', message: this.$t('message.cpm.validate.update_package.version.err2'), trigger: 'blur' }
            ],
            second: [
              // 请输入版本号
              { required: true, message: this.$t('message.cpm.validate.update_package.version.err1'), trigger: 'blur' },
              // 请输入正整数
              { type: 'integer', message: this.$t('message.cpm.validate.update_package.version.err2'), trigger: 'blur' }
            ],
            third: [
              // 请输入版本号
              { required: true, message: this.$t('message.cpm.validate.update_package.version.err1'), trigger: 'blur' },
              // 请输入正整数
              { type: 'integer', message: this.$t('message.cpm.validate.update_package.version.err2'), trigger: 'blur' }
            ]
          }
        }
      }
    }
  },
  mounted () {
    let self = this
    self.$nextTick(() => {
      self.getProductList()
    })
  },
  methods: {
    async getProductList () {
      let self = this
      try {
        self.product.list.loading = true
        let response = await self.$store.dispatch('axios', {
          method: 'get',
          url: `/api/abs/devices/device_product/`
        })
        self.product.list.data = response.data
      } finally {
        self.product.list.loading = false
      }
    },
    handleProductRowClick (row) {
      let self = this
      self.product.currentRow = row
      self.getPackageList()
    },
    handleProductCreate () {
      let self = this
      self.dialog.product.method = 'post'
      self.dialog.product.visible = true
    },
    async handleProductDelete (index, row) {
      let self = this
      try {
        // 此操作将永久删除${row.kind}产品，是否继续？
        await self.$confirm(self.$t('message.cpm.info.prompt.prompt1', { kind: row.kind }),
          self.$t('message.common.label.prompt'), {
            confirmButtonText: self.$t('message.common.button.confirm'),
            cancelButtonText: self.$t('message.common.button.cancel'),
            type: 'warning'
          })
      } catch (e) {
        return
      }
      await self.$store.dispatch(`axios`, {
        method: 'delete',
        url: `/api/abs/devices/device_product/${row.id}/`
      })
      // 产品删除成功
      self.$message.success(self.$t('message.cpm.info.message.msg1'))
      self.product.list.data.splice(index, 1)
    },
    async getPackageList () {
      let self = this
      try {
        self.update_package.list.loading = true
        let response = await self.$store.dispatch('axios', {
          method: 'get',
          url: `/api/abs/devices/update_package/`,
          params: {
            device_kind: self.product.currentRow.kind
          }
        })
        self.update_package.list.data = response.data
      } finally {
        self.update_package.list.loading = false
      }
    },
    handleUpdatePackageCreate () {
      let self = this
      self.dialog.update_package.method = 'post'
      self.dialog.update_package.visible = true
    },
    async submitForm (formName) {
      let self = this
      await self.$refs[formName].validate()
      if (formName === 'productForm') {
        try {
          self.dialog.product.buttonLoading = true
          if (self.dialog.product.method === 'post') {
            let response = await self.$store.dispatch('axios', {
              method: 'post',
              url: `/api/abs/devices/device_product/`,
              data: self.dialog.product.form
            })
            self.product.list.data.push(response.data)
            // 添加产品成功
            self.$message.success(self.$t('message.cpm.info.message.msg2'))
          }
        } finally {
          self.dialog.product.buttonLoading = false
        }
      }
      self.dialog.product.visible = false
    },
    async submitUpdatePackage (formName) {
      let self = this

      await self.$refs[formName].validate()

      let fileUpdate = document.getElementById('file').files[0]

      let formData = new FormData()
      formData.append('device_product', self.product.currentRow.id)
      formData.append('first', self.dialog.update_package.form.first)
      formData.append('second', self.dialog.update_package.form.second)
      formData.append('third', self.dialog.update_package.form.third)
      formData.append('describe', self.dialog.update_package.form.describe)
      formData.append('file', fileUpdate)

      try {
        self.dialog.update_package.buttonLoading = true
        let response = await self.$store.dispatch('axios', {
          method: 'post',
          url: '/api/abs/devices/update_package/',
          header: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData
        })

        self.update_package.list.data.push(response.data)
        // 添加升级包成功
        // self.$message.success(self.$t('message.cpm.info.message.msg3'))
        self.getPackageList()
      } finally {
        self.dialog.update_package.buttonLoading = false
      }
      self.dialog.update_package.visible = false
    },
    async handleUpdatePackageDelete (index, item) {
      let self = this
      try {
        // 此操作将永久删除${item.package_version}更新包，是否继续？
        await self.$confirm(self.$t('message.cpm.info.prompt.prompt2', { package_version: item.package_version }),
          self.$t('message.common.label.prompt'), {
            confirmButtonText: self.$t('message.common.button.confirm'),
            cancelButtonText: self.$t('message.common.button.cancel'),
            type: 'warning'
          })
      } catch (e) {
        return
      }
      await self.$store.dispatch(`axios`, {
        method: 'delete',
        url: `/api/abs/devices/update_package/${item.id}/`
      })
      // 更新包删除成功
      self.$message.success(self.$t('message.cpm.info.message.msg4'))
      self.update_package.list.data.splice(index, 1)
    }
  }
}
</script>

<style lang="scss">
  .product-div{
    cursor: pointer;
    box-sizing: border-box;
    .el-divider--horizontal{
      margin: 0;
    }
    &:hover{
      background-color: #8fe0ff;
    }
    .product-div-kind{
      height: 40px;
      line-height: 40px;
    }
  }
  .my-package-div{
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
  }
  .my-package-div-describe{
    text-align: left;
  }
  .my-package-div-button{
    text-align: right;
  }
  .version-input{
    width: 6em;
  }
</style>
